var dom = document.getElementById("container");
var myChart = echarts.init(dom);

function loadDataFromFile() {
    $.getJSON("response-throught.json", function(data){
        refreshNodes(data);
    }).fail(function(){
        console.log("An error has occurred.");
    });

}

function refreshNodes(data) {
    myChart.showLoading();

    const option = createOption(data);

    myChart.setOption(option);
    myChart.hideLoading();
}

function createXaxisData(data) {
    const ds = data.data.series[0].data;
    return ds.map(d=>moment(d.x).format('YYYY-MM-DD HH:mm'));
}
function createResponseTimeSeriesData(data) {
    const ds = data.data.series[0].data;
    return ds.map(d=>d.y);
}
function createThroughputSeriesData(data) {
    const ds = data.data.series[1].data;
    return ds.map(d=>d.y);
}

const intervalList = [1, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000];

function findInterval(max) {
    let interval=0;
    for (interval of intervalList) {
        if (max / interval < 10) {
            break;
        }
    }
    return interval;
}

function createAxisInfo(ds) {
    const max = Math.max(...ds);
    const interval = findInterval(max);
    return {
        max: (Math.trunc(max / interval) + 1) * interval,
        interval: interval
    }
}

function adjustAxisInfo(axis1, axis2) {
    const count = Math.max(axis1.max / axis1.interval, axis2.max / axis2.interval);
    axis1.max = count * axis1.interval;
    axis2.max = count * axis2.interval;
}

function createOption(data) {
    const rspTimes = createResponseTimeSeriesData(data);
    const rspAxis = createAxisInfo(rspTimes)

    const throughputs = createThroughputSeriesData(data);
    const throughputAxis = createAxisInfo(throughputs)

    adjustAxisInfo(rspAxis, throughputAxis);

    return {
        legend: {
            data: ['ResponseTime', 'Throughput']
        },
        xAxis: {
            type: 'category',
            data: createXaxisData(data)
        },
        yAxis: [{
            type: 'value',
            name: 'ResponseTime',
            min: 0,
            max: rspAxis.max,
            interval: rspAxis.interval,
            splitNumber: rspAxis.interval
        }, {
            type: 'value',
            name: 'Throughput',
            min: 0,
            max: throughputAxis.max,
            interval: throughputAxis.interval,
            splitNumber: throughputAxis.interval,
        }],
        series: [{
            name: 'ResponseTime',
            data: rspTimes,
            type: 'line'
        }, {
            name: 'Throughput',
            data: throughputs,
            type: 'bar',
            yAxisIndex: 1
        }]
    };
}
